#include "algo_belt.h"

#include "libbelt/BeltTearDetecteAlgo_V4.0.h"

#include <stdlib.h>

#include "util.h"
#include "modbus-srv.h"

#define BS_NORMAL 0 // 正常
#define BS_LASER_EXCEPTION 1 // 激光线异常
#define BS_TEAR 2 // 撕裂
#define BS_WATERDROP_COVER 4 // 水滴遮挡
#define BS_SLIME_COVER 8 // 煤泥遮挡

struct BeltTearParam* belt_param = NULL;

int init_belt(void* algo)
{
    belt_param = (struct BeltTearParam*)malloc(sizeof(struct BeltTearParam));
    if (!belt_param) {
        __log_mesg("malloc error.\n");
        return 1;
    }
    belt_param->ImgWidth = 1280;
    belt_param->ImgHeight = 1024;
    belt_param->LaserTH = 20;
    belt_param->LaserKernel = 5;
    belt_param->CameraFPS = 20;
    belt_param->ROI_LT_Point_x = 341;
    belt_param->ROI_LT_Point_y = 740;
    belt_param->ROI_RD_Point_x = 1014;
    belt_param->ROI_RD_Point_y = 835;
    belt_param->LaserWarningRate = 0.8;
    belt_param->LaserStdStep = 10;// 计算方差的设定步长
    belt_param->std_max = 100;
    belt_param->std_min = 5;
    belt_param->breakLaserNum = 10;
    belt_param->TearDuringTimes = 1; // 报警累计帧数统计  40
    belt_param->TearWarningDelay = 1; // 报警延时 40
    belt_param->TearWarningRate = 0.6; //计帧报警灵敏度0.4 越大越灵敏
    belt_param->TearTypeTH = 3;    // 皮带撕裂状态阈值
    belt_param->OutputLog = true;

    MT_BeltTearDetect_ImgProInit(belt_param);
    return 0;
}

void* compute_belt(void* algo, unsigned char* data, int width, int height)
{
    unsigned char status;
    static unsigned char laststatus = 0;
    MT_BeltTearDetect_Compute(data, status);
    if (status != laststatus) {
        char desc[256];
        sprintf(desc, "Belt detection result => [%d]\n", status);
        __log_mesg(desc);
    }
    set_input_register_uint16(status, TIE_BELT_STATUS_ADDR);
    laststatus = status;
    return NULL;
}

//void debug_debris(unsigned char* data, int width, int height);
void* analysis_belt(void* input)
{
    __log_mesg("No need to call analysis_belt.\n");
    return NULL;
}

int response_belt(void* algo, void* input)
{
    __log_mesg("No need to call response_belt.\n");
    return 1;
}

void destroy_belt(void* algo)
{
    if (belt_param) {
        free(belt_param);
        belt_param = 0;
    }
    MT_BeltTearDetect_Release();
}